<template>
  <div class="app-container">
    <!-- 订单管理 -->

    <div class="search-bar">
      <!-- 订单搜索 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="销售订单编号" prop="otherRef">
          <el-input
            v-noSpace
            v-model="queryParams.otherRef"
            class="!w-[192px]"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="客户编号" prop="companyCode">
          <el-input
            v-noSpace
            v-model="queryParams.companyCode"
            class="!w-[192px]"
            placeholder="请输入客户编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input
            v-noSpace
            v-model="queryParams.customerName"
            class="!w-[192px]"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractCode">
          <el-input
            v-noSpace
            v-model="queryParams.contractCode"
            class="!w-[192px]"
            placeholder="请输入合同编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="业务员" prop="salesMan">
          <el-select
            v-model="queryParams.salesMan"
            placeholder="请选择业务员"
            clearable
            filterable
            class="!w-[192px]"
            @visible-change="getSalesMan"
            @change="handleQuery"
          >
            <el-option
              v-for="item in optionsSalesMan"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="订单状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            class="!w-[192px]"
            @change="handleQuery"
          >
            <el-option label="待审核" :value="'0'" />
            <el-option label="审核拒绝" :value="'1'" />
            <el-option label="已审核" :value="'2'" />
            <el-option label="待入库" :value="'3'" />
            <el-option label="入库中" :value="'4'" />
            <el-option label="退货完成" :value="'5'" />
            <el-option label="取消退货" :value="'6'" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建日期" prop="timeScopes">
          <el-date-picker
            v-model="queryParams.timeScopes"
            type="datetimerange"
            placeholder="选择创建日期"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            picker-options="pickerOptions"
            clearable
            @change="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          <!-- <el-button type="warning" icon="menu" @click="handleOpenDialog({}, 'add')">
            新增
          </el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <!-- 订单列表 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="pageData">
        <el-table-column
          prop="code"
          label="退货订单编号"
          width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          prop="otherRef"
          label="销售订单编号"
          width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          prop="docType"
          label="订单类型"
          align="center"
          width="110"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span>
              {{ getDocTypeLabel(scope.row.docType) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          align="center"
          width="110"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="discountAmount"
          label="总金额"
          align="center"
          width="110"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.discountAmount.toFixed(2) + "元" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="discountRate"
          label="折扣率"
          align="center"
          width="110"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.discountRate.toFixed(2) + "%" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="companyCode"
          label="客户编号"
          align="center"
          width="110"
          show-overflow-tooltip
        />
        <el-table-column
          prop="customerName"
          label="客户名称"
          width="110"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          prop="contractCode"
          label="归属合同"
          align="center"
          width="110"
          show-overflow-tooltip
        />
        <el-table-column
          prop="salesMan"
          label="业务员"
          align="center"
          width="110"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{
              optionsSalesMan.filter((item) => item.value.toString() == scope.row.salesMan)[0]
                ?.label
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createName"
          label="创建人"
          align="center"
          width="110"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="110"
          show-overflow-tooltip
          align="center"
        />

        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column label="操作" fixed="right" min-width="350" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row, 'view')"
            >
              查看
            </el-button>
            <!-- 交付完成后8个小时内可以修改，超过就不行 -->
            <el-button
              v-if="scope.row.status == 0 || scope.row.status == 1"
              v-hasPerm="'sys:orderReturn:edit'"
              type="primary"
              link
              size="small"
              @click="handleOpenDialog(scope.row, 'edit')"
            >
              修改
            </el-button>
            <el-button
              v-hasPerm="'sys:orderReturn:del'"
              v-if="scope.row.status < 2"
              type="danger"
              link
              size="small"
              @click="handleOpenDialog(scope.row, 'del')"
            >
              删除
            </el-button>
            <el-button
              v-hasPerm="'sys:orderReturn:app'"
              v-if="scope.row.status == 0 || scope.row.status == 1"
              type="primary"
              link
              size="small"
              @click="handleApproved(scope.row)"
            >
              审核
            </el-button>
            <!-- <el-button type="primary" link size="small" @click="handleSetScale(scope.row)">
                  设置结算比例
                </el-button> -->

            <!-- <el-button
                  type="primary"
                  link
                  size="small"
                >
                  退货
                </el-button> -->

            <!-- <el-button type="primary" link size="small">退货</el-button> -->
            <el-button
              v-hasPerm="'sys:orderReturn:cancel'"
              v-if="scope.row.status < 2"
              type="primary"
              link
              size="small"
              @click="handleCanleReturn(scope.row)"
            >
              取消退货
            </el-button>
            <!-- <el-button
                  v-if="
                    scope.row.status == '0' || scope.row.status == '1' || scope.row.status == '2'
                  "
                  v-hasPerm="'sys:manage:app'"
                  type="primary"
                  link
                  size="small"
                  @click="handleApproved(scope.row)"
                >
                  审核
                </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormDataRef"
        :model="dialogFormData"
        :rules="rules"
        label-width="120px"
        :disabled="formDisabled"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="销售订单编号" prop="otherRef">
              <el-select
                v-model="dialogFormData.otherRef"
                placeholder="请选择销售订单编号"
                clearable
                filterable
                @change="changeCode"
                @visible-change="getCode"
                :disabled="dialog.title == '修改'"
              >
                <el-option
                  v-for="item in optionsName"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称">
              <el-input
                v-noSpace
                v-model="dialogFormData.customerName"
                placeholder="请输入客户名称"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户编号" prop="companyCode">
              <el-input
                v-noSpace
                v-model="dialogFormData.companyCode"
                placeholder="请输入客户编号"
                disabled
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="数量" prop="qty">
              <el-input-number v-model="dialogFormData.qty" placeholder="请输入" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="退货方式" prop="returnMethod">
              <el-select v-model="dialogFormData.returnMethod" placeholder="全部" clearable>
                <el-option label="退货退款" :value="'1'" />
                <el-option label="只退货" :value="'2'" />
                <el-option label="报废退货" :value="'3'" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dialogFormData.returnMethod !== '2'">
            <el-form-item label="折扣率" prop="discountRate">
              <el-input-number v-model="dialogFormData.discountRate" placeholder="请输入折扣率" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" v-if="dialogFormData.returnMethod !== '2'">
            <el-form-item label="折后金额" prop="discountAmount">
              <el-input-number v-model="dialogFormData.discountAmount" placeholder="请输入折扣率" />
            </el-form-item>
          </el-col> -->

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-noSpace
                v-model="dialogFormData.remark"
                :rows="4"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider />

      <!-- <p>{{ dialog.title == '新增'?'添加产品':'修改产品' }}</p> -->

      <el-form
        ref="dialogFormDataProRef"
        :model="dialogFormDataPro"
        :rules="rulesPro"
        label-width="120px"
        :disabled="formDisabled"
        v-if="dialogFormData.returnMethod !== '3' && dialog.title !== '查看'"
      >
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="产品类型" prop="productType">
              <el-input v-noSpace
                v-model="dialogFormDataPro.productType"
                placeholder="请输入产品类型"
                disabled
              />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input
                v-noSpace
                v-model="dialogFormDataPro.productCode"
                placeholder="请输入产品编号"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-select
                v-model="dialogFormDataPro.productName"
                placeholder="请选择产品名称"
                clearable
                filterable
                @change="changeProduct"
                @visible-change="searchCode"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="`数量（${unitFormat(dialogFormDataPro.unit) || ''}）`" prop="qty">
              <el-input-number
                v-model="productQty"
                :max="dialogFormDataPro.qty"
                placeholder="请输入数量"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number
                v-model="dialogFormDataPro.unitPrice"
                disabled
                placeholder="请输入单价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="rowRemark">
              <el-input
                v-noSpace
                v-model="dialogFormDataPro.rowRemark"
                :rows="2"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" />
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" @click="handleSavePro('continue')">添加产品</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        v-loading="loading"
        :data="rowTableData"
        :height="tableRowHight"
        v-if="dialogFormData.returnMethod !== '3'"
      >
        <!-- <el-table-column label="产品类型" align="center" prop="productType" />
        <el-table-column label="产品编号" align="center" prop="productCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="数量（kg）" align="center" prop="qty" />
        <el-table-column label="单价" align="center" prop="unitPrice" /> -->

        <el-table-column prop="productCode" label="产品编号" align="center" min-width="110" />
        <el-table-column prop="productName" label="产品名称" align="center" min-width="110" />
        <!-- 修改 quantity 和 price 列 -->
        <el-table-column label="每份数量" prop="qty" align="center" min-width="200">
          <template #default="scope">
            <div class="">
              {{ scope.row.qty }}
              {{ unitFormat(scope.row.unit) }}
            </div>
          </template>
        </el-table-column>
        <!-- <template #default="scope">
            <el-input v-noSpace
              v-model="scope.row.quantity"
              @keyup.enter="handleUpdate(scope.row, 'quantity')"
            />
          </template>
        </el-table-column> -->
        <el-table-column label="单价(元)" prop="unitPrice" align="center" min-width="200" />
        <!-- <template #default="scope">
            <el-input v-noSpace v-model="scope.row.price" @keyup.enter="handleUpdate(scope.row, 'price')" />
          </template>
        </el-table-column> -->
        <el-table-column prop="rowRemark" label="备注" show-overflow-tooltip align="center" />
        <el-table-column
          label="操作"
          fixed="right"
          min-width="70"
          align="center"
          v-if="dialog.title !== '查看'"
        >
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              link
              @click="handleRowDialog(scope.row, scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <p class="df-fe">总退款金额：￥6700</p> -->
      <template #footer>
        <div v-if="buttonIsishow" class="dialog-footer flex-center">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <!-- <el-button type="primary" @click="handleSubmit('save')">暂 存</el-button> -->
          <el-button
            v-if="dialog.title == '新增' || dialog.title == '修改'"
            v-debounce="handleSubmit"
            type="primary"
          >
            提 交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加产品 -->
    <!-- <el-dialog
      v-model="dialogPro.visible"
      :title="dialogPro.title"
      width="500px"
      @close="handleCloseDialogPro"
    >
      <el-form
        ref="dialogFormDataProRef"
        :model="dialogFormDataPro"
        :rules="rulesPro"
        label-width="150px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="结算费用折扣比例" prop="qty">
              <el-input-number v-model="dialogFormDataPro.qty" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="赔偿金额（元）" prop="qty">
              <el-input-number v-model="dialogFormDataPro.qty" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="退货情况说明" prop="remark">
              <el-input v-noSpace
                v-model="dialogFormDataPro.remark"
                :rows="4"
                type="textarea"
                placeholder="请输入退货情况说明"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handleSavePro('save')">提 交</el-button>
        </div>
      </template>
    </el-dialog> -->

    <!-- 审核 -->
    <el-dialog
      v-model="dialogApp.visible"
      :title="dialogApp.title"
      width="500px"
      @close="handleCloseDialogApp"
    >
      <el-input v-noSpace v-model="approvedRemake" type="textarea" placeholder="请输入审核意见" />

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handlePass('pass')">通 过</el-button>
          <el-button type="primary" @click="handlePass('noPass')">拒绝</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除 -->
    <el-dialog
      v-model="dialogDel.visible"
      :title="dialogDel.title"
      width="500px"
      @close="handleCloseDialogDel"
    >
      <p>删除后数据将不可显示，且本条库存数据清空，确认是否继续？</p>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handleDel()">确 定</el-button>
          <el-button @click="dialogDel.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import orderReturnAPI, {
  orderReturnPageQuery,
  orderReturnPageVO,
  orderReturnInfo,
  orderReturnDetail,
} from "@/api/orderReturn/orderReturn";
import configApi, { ConfigType } from "@/api/config/config";
import { FormItemRule } from "element-plus/es";

import UserAPI from "@/api/system/user";

// 列表高度
const tableHight = `400px`;
// Row列表高度
const tableRowHight = `250px`;

//row列表数据
const rowTableData = ref<orderReturnDetail[]>();

const formDisabled = ref(false);

//row信息
const rowObj = ref<orderReturnPageVO | null>(null);
const orderAmount = ref("");

//暂存 按钮isShow
const buttonIsishow = ref(false);
//暂存 按钮类型判断新增还是修改
const savebutIsType = ref("");

// 新增弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 新增弹窗
const dialogPro = reactive({
  title: "",
  visible: false,
});

//// 审核弹窗
const dialogApp = reactive({
  title: "",
  visible: false,
});

//// 审核弹窗
const dialogDel = reactive({
  title: "",
  visible: false,
});

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const queryParams = reactive<orderReturnPageQuery>({
  isReturnOrder: 1,
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<orderReturnPageVO[]>();
const total = ref(0);
const loading = ref(false);

// 新增/修改form
const dialogFormData = reactive<orderReturnInfo>({
  id: 0,
  /** 销售订单编号 */
  code: "",
  otherRef: "",
  /** 客户名称 */
  customerName: "",

  /** 客户编号 */
  companyCode: undefined,

  /** 数量 */
  qty: 0,

  /** 折扣率 */
  discountRate: 0,

  /** 折后金额 */
  discountAmount: 0,

  /** 备注 */
  remark: "",

  salesOrderDetailList: [] as orderReturnDetail[],

  /** 判断是否退货 */
  isReturnOrder: 1,
  /** 合同编号 */
  contractCode: "",
  /** 业务员 */
  salesMan: "",

  returnMethod: "",
});

const dialogFormDataRef = ref(ElForm);

const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const optionsSalesMan = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const optionsName = ref<{ value: string; label: string }[]>([]); // 显式指定类型

// 添加产品
const dialogFormDataPro = reactive<orderReturnDetail>({
  productType: "",
  productCode: "",
  productName: "",
  qty: 0,
  unitPrice: 0,
  remark: "",
});

const dialogFormDataProRef = ref(ElForm);

// 审核意见
const approvedRemake = ref("");

const rules = reactive<Record<string, FormItemRule[]>>({
  code: [{ required: true, message: "销售订单编号是必填项", trigger: "blur" }],
  returnMethod: [{ required: true, message: "退货方式是必填项", trigger: "blur" }],
  customerName: [{ required: true, message: "客户名称是必填项", trigger: "blur" }],
  qty: [
    { required: true, message: "数量是必填项", trigger: "blur" },
    { type: "number", message: "数量必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "数量必须大于等于0", trigger: "blur" },
  ],
  discountRate: [
    { required: true, message: "折扣率是必填项", trigger: "blur" },
    { type: "number", message: "折扣率必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "折扣率必须大于等于0", trigger: "blur" },
  ],
  discountAmount: [
    { required: true, message: "折扣率是必填项", trigger: "blur" },
    { type: "number", message: "折扣率必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "折扣率必须大于等于0", trigger: "blur" },
  ],

  // currency: [{ required: true, message: "币别是必填项", trigger: "blur" }],
  // discountAmount: [
  //   { required: true, message: "折扣金额是必填项", trigger: "blur" },
  //   { type: "number", message: "折扣金额必须是一个数字", trigger: "blur" },
  //   { min: 0, message: "折扣金额必须大于等于0", trigger: "blur" },
  // ],
  // deliveryDate: [
  //   { required: true, message: "送货日期是必填项", trigger: "change" },
  //   { type: "date", message: "请选择有效的日期", trigger: "change" },
  // ],
  // issueDate: [
  //   { required: true, message: "单据日期是必填项", trigger: "change" },
  //   { type: "date", message: "请选择有效的日期", trigger: "change" },
  // ],
  // dueDate: [
  //   { required: true, message: "有效日期是必填项", trigger: "change" },
  //   { type: "date", message: "请选择有效的日期", trigger: "change" },
  // ],
  // refCode: [{ required: true, message: "参考编号是必填项", trigger: "blur" }],
  // otherRef: [{ required: true, message: "其它参考编号是必填项", trigger: "blur" }],
  // paymentTerm: [{ required: true, message: "付款条款是必填项", trigger: "blur" }],
  // salesMan: [{ required: true, message: "销售人员是必填项", trigger: "blur" }],
  // tradeTerm: [{ required: true, message: "贸易条款是必填项", trigger: "blur" }],
  // shippingTerm: [{ required: true, message: "付运条款是必填项", trigger: "blur" }],
  // shippingMark: [{ required: true, message: "箱唛是必填项", trigger: "blur" }],
  // packing: [{ required: true, message: "包装信息是必填项", trigger: "blur" }],
  // shippingSideMark: [{ required: true, message: "纸箱侧唛是必填项", trigger: "blur" }],
  // shipCode: [{ required: true, message: "送货地址是必填项", trigger: "blur" }],
});

const rulesPro = reactive<Record<string, FormItemRule[]>>({
  productName: [{ required: true, message: "产品名称是必填项", trigger: "blur" }],
  qty: [
    { required: true, message: "数量是必填项", trigger: ["blur", "change"] },
    { type: "number", message: "数量必须是一个数字", trigger: ["blur", "change"] },
    { min: 1, type: "number", message: "数量必须大于等于0", trigger: ["blur", "change"] },
  ],
  // returnMethod: [{ required: true, message: "退货方式是必填项", trigger: "blur" }],
  unitPrice: [
    { required: true, message: "单价是必填项", trigger: "blur" },
    { type: "number", message: "单价必须是一个数字", trigger: "blur" },
    { min: 1, type: "number", message: "单价必须大于等于0", trigger: "blur" },
  ],
  discountAmount: [
    { required: true, message: "折扣金额是必填项", trigger: "blur" },
    { type: "number", message: "折扣金额必须是一个数字", trigger: "blur" },
    { min: 0, type: "number", message: "折扣金额必须大于等于0", trigger: "blur" },
  ],
});
// 选中的用户ID
const selectIds = ref<number[]>([]);
// 部门下拉数据源
const deptOptions = ref<OptionType[]>();
// 角色下拉数据源
const roleOptions = ref<OptionType[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
function handleQuery() {
  loading.value = true;
  buttonIsishow.value = false;
  orderReturnAPI
    .getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
      orderAmount.value = "0";
      rowTableData.value = [];
    })
    .catch((error) => {
      // //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  rowTableData.value = [];
  handleQuery();
}

// 新增/修改
function handleOpenDialog(row: orderReturnPageVO | null = null, type: string) {
  let upData = {};
  if (type == "view") {
    dialog.visible = true;

    upData = { ...row };
    Object.assign(dialogFormData, upData);
    dialog.title = "查看";
    if (row) {
      handleRowClick(row, {}, null);
    }
    buttonIsishow.value = false;
    formDisabled.value = true;
    clearDialogFormDataPro();
  } else if (type == "add") {
    dialog.visible = true;
    dialog.title = "新增";
    console.log("dialog.title", dialog.title);
    buttonIsishow.value = true; //按钮
    savebutIsType.value = "add"; //暂存类型判断
    formDisabled.value = false;
    rowTableData.value = [];
    clearDialogFormData();
    clearDialogFormDataPro();
  } else if (type == "del") {
    upData = { ...row };
    Object.assign(dialogFormData, upData);
    dialogDel.title = "删除";
    dialogDel.visible = true;
  } else {
    dialog.visible = true;
    upData = { ...row };
    rowObj.value = { ...row };
    if (rowObj.value) {
      handleRowClick(row, {}, null);
    }
    Object.assign(dialogFormData, upData);
    dialog.title = "修改";
    buttonIsishow.value = true;
    savebutIsType.value = "edit"; //暂存类型判断
    formDisabled.value = false;
  }
}

//设置比例

function handleSetScale(row: any) {
  console.log("设置比例");
  dialogPro.visible = true;
}
//随机数
// function generateRandomId(length = 10) {
//   let result = 0;
//   for (let i = 0; i < length; i++) {
//     // 每次循环生成一个0到9之间的随机数
//     const digit = Math.floor(Math.random() * 10);
//     // 将生成的随机数加到结果上，并乘以10以腾出下一位的位置
//     result = result * 10 + digit;
//   }
//   return result;
// }

//审核
function handleApproved(row: orderReturnPageVO | null = null) {
  if (row) {
    // approvedRemake.value = row.appRemake || "";
    rowObj.value = { ...row };
    dialogApp.visible = true;
    dialogApp.title = "审核意见";
    approvedRemake.value = row?.approvalComment || ""; // 使用可选链操作符并提供默认值
  } else {
    console.warn("handleApproved函数被调用时，row参数为null。");
  }
}

// 新增的方法：处理行点击事件
function handleRowClick(row: any, column: any, event: MouseEvent | null) {
  rowObj.value = { ...row };
  buttonIsishow.value = true;
  orderReturnAPI
    .getTorderReturnDetailByCode(row.code)
    .then((data) => {
      rowTableData.value = data?.detailList;
      orderAmount.value = data?.orderAmount;
      // ElMessage.success(`保存成功`);
    })
    .catch((error) => {
      // //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  dialogFormDataRef.value?.clearValidate();
  dialogFormDataRef.value?.resetFields();
  // userFormRef.value.resetFields();
  // userFormRef.value.clearValidate();

  // formData.id = undefined;
  // formData.status = 1;
  productQty.value = 0;
}
const productQty = ref(0);

function handleSavePro(type: string) {
  dialogFormDataProRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    const isDuplicate = rowTableData.value?.some(
      (item: any) => item.productCode === dialogFormDataPro.productCode
    );
    if (isDuplicate) {
      ElMessage.error("该产品名称已存在，请勿重复添加");
      return;
    }
    rowTableData.value?.push({
      productType: dialogFormDataPro.productType,
      productCode: dialogFormDataPro.productCode,
      productName: dialogFormDataPro.productName,
      qty: productQty.value,

      unitPrice: dialogFormDataPro.unitPrice,
      // returnMethod: dialogFormDataPro.returnMethod,
      rowRemark: dialogFormDataPro.rowRemark,
      unit: dialogFormDataPro.unit,
    });
    ElMessage.success("添加成功");
    clearDialogFormDataPro();
  });
}

//是否通过
function handlePass(type: string) {
  const status = type === "pass" ? 2 : 1;
  orderReturnAPI
    .editTSalesOrder({
      id: rowObj.value?.id,
      status: status,
      approvalComment: approvedRemake.value,
    })
    .then((data) => {
      ElMessage.success(`操作成功`);
      handleQuery();
      dialogApp.visible = false;
      approvedRemake.value = "";
    })
    .catch((error) => {
      // //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleDel() {
  orderReturnAPI
    .rowDel({ id: dialogFormData?.id })
    .then((data) => {
      ElMessage.success(`操作成功`);
      handleQuery();
      dialogDel.visible = false;
    })
    .catch((error) => {
      // //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
}

function handleCloseDialogPro() {
  dialogPro.visible = false;
}

function handleCloseDialogApp() {
  dialogApp.visible = false;
}

function handleCloseDialogDel() {
  dialogDel.visible = false;
}

function addPro() {
  dialogPro.visible = true;
  // // 清空表单数据
  let data = {
    qty: 0,
    unit: "",
    unitPrice: 0,
    rowRemark: "",
    customerSku: "",
    sourceCode: "",
    parentCode: "",
    description: "",
    discountAmount: 0,
  };
  Object.assign(dialogFormDataPro, { ...data });
}
function clearDialogFormDataPro() {
  let data = {
    qty: 0,
    productType: "",
    unitPrice: 0,
    productCode: "",
    productName: "",
    returnMethod: "",
    rowRemark: "",
    remark: "",
  };
  Object.assign(dialogFormDataPro, { ...data });
}

function clearDialogFormData() {
  let data = {
    id: undefined,
    /** 销售订单编号 */
    code: "",
    otherRef: "",
    /** 客户名称 */
    customerName: "",

    /** 客户编号 */
    companyCode: undefined,

    /** 数量 */
    qty: 0,

    /** 折扣率 */
    discountRate: 0,

    /** 折后金额 */
    discountAmount: 0,

    /** 备注 */
    remark: "",

    salesOrderDetailList: [] as orderReturnDetail[],

    /** 判断是否退货 */
    isReturnOrder: 1,
    /** 合同编号 */
    contractCode: "",
    /** 业务员 */
    salesMan: "",
    /** 退货方式 */
    returnMethod: "",
  };
  Object.assign(dialogFormData, { ...data });
}
// 提交用户表单（防抖）
// const handleSubmit = useDebounceFn(() => {
//   userFormRef.value.validate((valid: boolean) => {
//     if (valid) {
//       const userId = formData.id;
//       loading.value = true;
//       if (userId) {
//         ManageAPI.update(userId, formData)
//           .then(() => {
//             ElMessage.success("修改用户成功");
//             handleCloseDialog();
//             handleResetQuery();
//           })
//           .finally(() => (loading.value = false));
//       } else {
//         ManageAPI.add(formData)
//           .then(() => {
//             ElMessage.success("新增用户成功");
//             handleCloseDialog();
//             handleResetQuery();
//           })
//           .finally(() => (loading.value = false));
//       }
//     }
//   });
// }, 1000);

// 新增提交
function handleSubmit() {
  dialogFormDataRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    if (!rowTableData?.value?.length && dialogFormData.returnMethod !== "3")
      return ElMessage.error("请添加产品列表");
    dialogFormData.salesOrderDetailList = rowTableData.value;
    dialogFormData.salesOrderDetailList = dialogFormData.salesOrderDetailList?.map((item) => {
      if (dialog.title === "新增") {
        const { id, ...rest } = item; // 使用对象解构去掉 id 属性
        return { ...rest, returnMethod: dialogFormData.returnMethod }; // 添加 returnMethod 属性
      } else {
        return { ...item, returnMethod: dialogFormData.returnMethod }; // 保留 id 属性
      }
    });

    let paramData = <orderReturnInfo>{};
    if (dialog.title == "新增") {
      paramData.code = dialogFormData.otherRef;
      paramData.otherRef = dialogFormData.otherRef;
      paramData.contractCode = dialogFormData.contractCode;
      paramData.salesMan = dialogFormData.salesMan;
      paramData.customerName = dialogFormData.customerName;
      paramData.companyCode = dialogFormData.companyCode;
      paramData.qty = dialogFormData.qty;
      paramData.discountRate = dialogFormData.discountRate;
      paramData.discountAmount = dialogFormData.discountAmount;
      paramData.remark = dialogFormData.remark;
      paramData.salesOrderDetailList = dialogFormData.salesOrderDetailList;
      paramData.status = dialogFormData.status;
      paramData.docType = dialogFormData.docType;
    } else {
      paramData = { ...dialogFormData };
    }
    paramData.isReturnOrder = 1;

    // 根据 dialog.title 判断调用哪个方法
    const reqMethod =
      dialog.title === "新增" ? orderReturnAPI.saveOrUpdateTSalesOrder : orderReturnAPI.editStatus;
    reqMethod(paramData)
      .then((data) => {
        console.log(paramData, "新增");

        ElMessage.success(`操作成功`);
        handleQuery();
        handleCloseDialog();
        clearDialogFormData();
      })
      .catch((error) => {
        // //ElMessage.error(`${error}`); //注释报错弹窗
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

const statusMap: any = {
  0: { label: "待审核", type: "warning" },
  1: { label: "审核拒绝", type: "danger" },
  2: { label: "已审核", type: "success" },
  3: { label: "待入库", type: "warning" },
  4: { label: "入库中", type: "warning" },
  5: { label: "退货完成", type: "success" },
  6: { label: "取消退货", type: "success" },
};

function getStatusLabel(status: number) {
  return statusMap[status as keyof typeof statusMap]?.label || "未知状态";
}

function getStatusType(status: number) {
  return statusMap[status as keyof typeof statusMap]?.type || "未知状态";
}

const docTypeMap = {
  0: { label: "周期订单" },
  1: { label: "紧急订单" },
};

function getDocTypeLabel(status: number) {
  return docTypeMap[status as keyof typeof docTypeMap]?.label || "未知状态";
}

const returnMethodMap = {
  1: { label: "退货退款" },
  2: { label: "只退货" },
  3: { label: "报废退货" },
};

function getReturnMethod(status: number) {
  return returnMethodMap[status as keyof typeof returnMethodMap]?.label || "未知状态";
}

const getSalesMan = () => {
  UserAPI.getPage({ pageNum: 1, pageSize: 999, roleName: "salesMan" }).then((data) => {
    optionsSalesMan.value = data.list.map((item: any) => ({
      value: item.id,
      label: item.name,
    }));
  });
};
// 选中产品单位值
const unitValue = ref<{ label?: string; value?: string }>({});
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};
const unitFormat = (unit: any) => {
  console.log(unit, "unit");
  let unitLabel = unitOptions.value.find((item) => item.value === unit)?.label;
  return unitLabel;
};
function changeProduct(val: any) {
  console.log(val, "changeProduct");
  dialogFormDataPro.productCode = val.value;
  dialogFormDataPro.productName = val.label;
  dialogFormDataPro.qty = val.qty;
  dialogFormDataPro.unitPrice = val.unitPrice;
  dialogFormDataPro.rowRemark = val.rowRemark;
  dialogFormDataPro.unit = val.unit;
  productQty.value = val.qty;
}

const getCode = () => {
  orderReturnAPI
    .getCodeList({ pageNum: 1, pageSize: 20, isReturnOrder: 0, status: 2, statusList: [2] })
    .then((data: any) => {
      optionsName.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.code,
        contractCode: item.contractCode,
        salesMan: item.salesMan,
        customerName: item.customerName,
        companyCode: item.companyCode,
        status: item.status,
        docType: item.docType,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};

const getProductType = () => {
  orderReturnAPI
    .getTypePage({ pageNum: 1, pageSize: 20 })
    .then((data) => {
      options.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
        productType: item.categoryName,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};
const getName = () => {
  orderReturnAPI
    .getcusName({ pageNum: 1, pageSize: 20 })
    .then((data) => {
      optionsName.value = (data?.list || []).map((item: any) => ({
        value: item.companyCode,
        label: item.companyName,
      }));
    })
    .finally(() => {
      loading.value = false;
    });
};
function changeName(val: any) {
  dialogFormData.customerName = val.label;
  dialogFormData.companyCode = val.value;
}

function changeCode(val: any) {
  console.log(val, "val");

  dialogFormData.code = val.value;
  if (dialogFormData.code) {
    searchCode(val.value);
  }
  dialogFormData.contractCode = val.contractCode;
  dialogFormData.salesMan = val.salesMan;
  dialogFormData.customerName = val.customerName;
  dialogFormData.companyCode = val.companyCode;
  dialogFormData.status = val.status;
  dialogFormData.docType = val.docType;
  dialogFormData.discountAmount = val.discountAmount;
  dialogFormData.discountRate = val.discountRate;
}

function handleRowDialog(row: any, index: any) {
  if (index !== -1) {
    rowTableData?.value?.splice(index, 1);
    ElMessage.success(`删除成功`);
  }
}

function handleCanleReturn(row: any) {
  orderReturnAPI
    .editStatus({ id: row?.id, status: 6 })
    .then((data) => {
      ElMessage.success(`取消退货成功`);
      handleQuery();
    })
    .catch((error) => {
      // //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
}

function searchCode(code: any) {
  orderReturnAPI
    .searchCode(dialogFormData?.otherRef)
    .then((data) => {
      options.value = (data?.detailList || []).map((item: any) => ({
        value: item.productCode,
        label: item.productName,
        qty: item.qty,
        rowRemark: item.rowRemark,
        unitPrice: item.unitPrice,
        unit: item.unit,
      }));
      console.log(options.value, "options.value");
      // rowTableData.value = data?.detailList || [];
      // ElMessage.success(`取消退货成功`);
      // handleQuery();
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {});
}

function handleUpdate(row: any, type: any) {}

onMounted(() => {
  handleQuery();
  getUnitList();
  getSalesMan();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
